import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { Language, t as translateFunc } from './translations';

// 语言上下文类型
interface LanguageContextType {
  currentLanguage: Language;
  setLanguage: (language: Language) => void;
}

// 国际化上下文类型
interface I18nContextType {
  language: Language;
  setLanguage: (language: Language) => void;
  t: (key: string) => string;
}

// 创建默认上下文值
const defaultI18nContextValue: I18nContextType = {
  language: 'zh-CN',
  setLanguage: () => {},
  t: (key) => key,
};

// 创建默认语言上下文值
const defaultLanguageContextValue: LanguageContextType = {
  currentLanguage: 'zh-CN',
  setLanguage: () => {},
};

// 创建国际化上下文
export const I18nContext = createContext<I18nContextType>(defaultI18nContextValue);

// 创建语言上下文
export const LanguageContext = createContext<LanguageContextType>(defaultLanguageContextValue);

// 国际化提供者组件的属性类型
interface I18nProviderProps {
  children: ReactNode;
  defaultLanguage?: Language;
}

// 国际化提供者组件
export const I18nProvider: React.FC<I18nProviderProps> = ({ 
  children, 
  defaultLanguage = 'zh-CN' 
}) => {
  // 从本地存储中获取用户之前选择的语言，或使用默认语言
  const [language, setLanguage] = useState<Language>(() => {
    const savedLanguage = localStorage.getItem('app-language');
    return (savedLanguage as Language) || defaultLanguage;
  });

  // 当语言改变时，保存到本地存储
  useEffect(() => {
    localStorage.setItem('app-language', language);
  }, [language]);

  // 翻译函数
  const t = (key: string): string => {
    return translateFunc(key, language);
  };

  // 上下文值
  const contextValue: I18nContextType = {
    language,
    setLanguage,
    t,
  };

  return (
    <I18nContext.Provider value={contextValue}>
      {children}
    </I18nContext.Provider>
  );
};

// 使用国际化的自定义钩子
export const useI18n = (): I18nContextType => {
  const context = useContext(I18nContext);
  if (!context) {
    throw new Error('useI18n must be used within an I18nProvider');
  }
  return context;
};

// 使用语言Hook
export const useLanguage = (): LanguageContextType => useContext(LanguageContext);

// 再导出翻译函数和语言类型
export { translateFunc as t };
export type { Language };

// 默认导出
export default {
  I18nProvider,
  useI18n,
  useLanguage,
  t: translateFunc
};

// 基础消息映射，用于本地使用
export const messages = {
  'zh-CN': {
    app: {
      title: 'Dep Vista - 依赖可视化工具',
      loading: '加载中...',
      error: '错误',
      noData: '没有数据',
      refresh: '刷新',
      back: '返回',
      confirm: '确认',
      cancel: '取消',
      close: '关闭',
      save: '保存'
    },
    nav: {
      dashboard: '概览',
      projects: '项目',
      files: '文件',
      cleanup: '清理工具'
    },
    dashboard: {
      title: '概览',
      totalProjects: '项目总数',
      totalSize: '总大小',
      nodeModulesSize: 'node_modules大小',
      scanTime: '扫描时间',
      rescan: '重新扫描'
    },
    projects: {
      title: '项目列表',
      name: '名称',
      type: '类型',
      path: '路径',
      size: '大小',
      dependencies: '依赖',
      devDependencies: '开发依赖',
      children: '子项目',
      loadingSize: '计算大小中...',
      loadSize: '加载大小'
    },
    files: {
      title: '文件浏览器',
      name: '名称',
      type: '类型',
      path: '路径',
      size: '大小',
      modified: '修改时间',
      directory: '目录',
      file: '文件',
      loadingContent: '加载内容中...'
    },
    cleanup: {
      title: '清理工具',
      description: '用于清理项目中的无用文件和目录',
      nodeModules: '清理所有 node_modules',
      unusedDeps: '检测未使用的依赖',
      duplicateDeps: '检测重复依赖',
      analyzing: '分析中...',
      clean: '清理',
      detect: '检测',
      noItemsFound: '没有找到可清理的项目'
    }
  },
  'en-US': {
    app: {
      title: 'Dep Vista - Dependency Visualization Tool',
      loading: 'Loading...',
      error: 'Error',
      noData: 'No Data',
      refresh: 'Refresh',
      back: 'Back',
      confirm: 'Confirm',
      cancel: 'Cancel',
      close: 'Close',
      save: 'Save'
    },
    nav: {
      dashboard: 'Dashboard',
      projects: 'Projects',
      files: 'Files',
      cleanup: 'Cleanup'
    },
    dashboard: {
      title: 'Dashboard',
      totalProjects: 'Total Projects',
      totalSize: 'Total Size',
      nodeModulesSize: 'node_modules Size',
      scanTime: 'Scan Time',
      rescan: 'Rescan'
    },
    projects: {
      title: 'Project List',
      name: 'Name',
      type: 'Type',
      path: 'Path',
      size: 'Size',
      dependencies: 'Dependencies',
      devDependencies: 'Dev Dependencies',
      children: 'Sub Projects',
      loadingSize: 'Calculating size...',
      loadSize: 'Load Size'
    },
    files: {
      title: 'File Browser',
      name: 'Name',
      type: 'Type',
      path: 'Path',
      size: 'Size',
      modified: 'Modified',
      directory: 'Directory',
      file: 'File',
      loadingContent: 'Loading content...'
    },
    cleanup: {
      title: 'Cleanup Tools',
      description: 'Clean unused files and directories in your projects',
      nodeModules: 'Clean all node_modules',
      unusedDeps: 'Detect unused dependencies',
      duplicateDeps: 'Detect duplicate dependencies',
      analyzing: 'Analyzing...',
      clean: 'Clean',
      detect: 'Detect',
      noItemsFound: 'No items found to clean'
    }
  }
} as const;

// 获取内部翻译文本，提供一个直接使用本地messages的函数
export const getMessage = (key: string, language: Language = 'zh-CN'): string => {
  const keys = key.split('.');
  let result: any = messages[language];
  
  for (const k of keys) {
    if (result && result[k]) {
      result = result[k];
    } else {
      return key; // 如果找不到翻译，返回原始key
    }
  }
  
  return typeof result === 'string' ? result : key;
}; 